﻿using Microsoft.AspNetCore.Mvc;
using lesson10.Models;
using System.Collections.Generic;
using System.Linq;
using lesson10.Models;

namespace lesson10.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ToDoController : ControllerBase
    {
        private static List<ToDoItem> toDos = new List<ToDoItem>
        {
            new ToDoItem { Id = 1, Title = "完成作业", IsCompleted = false },
            new ToDoItem { Id = 2, Title = "锻炼身体", IsCompleted = true }
        };

        [HttpGet]
        public ActionResult<IEnumerable<ToDoItem>> GetAll() => Ok(toDos);

        [HttpGet("{id}")]
        public ActionResult<ToDoItem> GetById(int id)
        {
            var item = toDos.FirstOrDefault(t => t.Id == id);
            if (item == null) return NotFound();
            return Ok(item);
        }

        [HttpPost]
        public ActionResult<ToDoItem> Create(ToDoItem item)
        {
            item.Id = toDos.Count > 0 ? toDos.Max(t => t.Id) + 1 : 1;
            toDos.Add(item);
            return CreatedAtAction(nameof(GetById), new { id = item.Id }, item);
        }

        [HttpPut("{id}")]
        public IActionResult Update(int id, ToDoItem updatedItem)
        {
            var item = toDos.FirstOrDefault(t => t.Id == id);
            if (item == null) return NotFound();

            item.Title = updatedItem.Title;
            item.IsCompleted = updatedItem.IsCompleted;
            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var item = toDos.FirstOrDefault(t => t.Id == id);
            if (item == null) return NotFound();

            toDos.Remove(item);
            return NoContent();
        }
    }
}
